const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
_states = PENDING
class MyPromise {
    constructor(fun) {
        this.states = PENDING
        this.value = null
        this.reason = null
        this.onResolvedCallbacks = []
        this.onRejectedCallbacks = []
        try {
            fun(this.resolve.bind(this), this.reject.bind(this));
        } catch (e) {
            this.reject(e)
        }
    }
    resolve(value) {
        if (this.states === PENDING) {
            this.states = FULFILLED
            this.value = value
            (this.onResolvedCallbacks || []).forEach(func => func())
        }
    }
    reject(reason) {
        if (this.states === PENDING) {
            this.states = REJECTED
            this.reason = reason
            (this.onRejectedCallbacks || []).forEach(func => func())
        }
    }
    then(onFulfilled, onRejected) {
        if (this.states === FULFILLED) {
            onFulfilled(this.value)
        }
        if (this.states === REJECTED) {
            onRejected(this.reason)
        }
        if (this.states === PENDING) {
            this.onResolvedCallbacks.push(() => {
                onFulfilled(this.value)
            })
            this.onRejectedCallbacks.push(() => {
                onRejected(this.reason)
            })
        }
    }
}

const myPromise = MyPromise((resolve, rejecte) => {
    resolve('OK')
}).then((reason) => {
    console.log(reason)
})